﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Windows.Forms;
using Microsoft.Win32;

namespace Movistar.SMS.OutlookAddIn
{
    partial class AppRegion
    {
        private RemindersDB remindersDB = null;
        private Outlook.AppointmentItem currentAppointment = null;
        private int currentAppID = -1;
        private DateTime currentAppOccurs;
        private ToolStripMenuItem customMsgItem = null;
        private bool appointmentDirty = false;
        private bool appointmentEnabled = false;

        #region Form Region Factory

        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Appointment)]
        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass("IPM.Appointment")]
        [Microsoft.Office.Tools.Outlook.FormRegionName("Movistar.SMS.OutlookAddIn.AppRegion")]
        public partial class SMSReminderRegionFactory
        {
            // Occurs before the form region is initialized.
            // To prevent the form region from appearing, set e.Cancel to true.
            // Use e.OutlookItem to get a reference to the current Outlook item.
            private void SMSReminderRegionFactory_FormRegionInitializing(object sender, Microsoft.Office.Tools.Outlook.FormRegionInitializingEventArgs e)
            {
            }
        }

        #endregion

        #region Form Open/Close
        // Occurs before the form region is displayed.
        // Use this.OutlookItem to get a reference to the current Outlook item.
        // Use this.OutlookFormRegion to get a reference to the form region.
        private void SMSReminderRegion_FormRegionShowing(object sender, System.EventArgs e)
        {
            currentAppointment = (Outlook.AppointmentItem)this.OutlookItem;

            try
            {
                RegistryKey key = Registry.LocalMachine.OpenSubKey(OutlookAddIn.Properties.Settings.Default.RegKeyAddIn);

                remindersDB = new RemindersDB(key.GetValue(OutlookAddIn.Properties.Settings.Default.RegKeyDB).ToString());

                var appointment = from appointments in remindersDB.Appointments
                                  where appointments.OutlookID == currentAppointment.GlobalAppointmentID
                                  select appointments;

                if (appointment.Count() == 0)
                {
                    tabControl1.TabPages.Remove(tabConfig);
                    tabControl1.TabPages.Remove(tabMessageText);
                    tabControl1.TabPages.Remove(tabHistoric);
                }
                else
                {
                    appointmentEnabled = true;

                    Appointments currentApp = appointment.Single();

                    currentAppID = currentApp.AppointmentID_;
                    currentAppOccurs = currentApp.Occurs;

                    tabControl1.TabPages.Remove(tabNoConfig);

                    edContacts.Text = currentApp.To;
                    edMessage.Text = currentApp.CustomMessage;  // Custom message is saved/loaded even if not selected

                    int[] actualReminders = (from apprem in remindersDB.AppointmentReminders
                                             where apprem.AppointmentID_ == currentApp.AppointmentID_
                                             select apprem.ReminderID_).ToArray<int>();

                    if (actualReminders.Count() == 0)
                        actualReminders = null;

                    if (currentApp.TemplateID_ != null)
                        LoadReminderAndTemplateControls((int)currentApp.TemplateID_, actualReminders);
                    else
                        LoadReminderAndTemplateControls(-1, actualReminders); // No template selected

                    if (currentApp.TemplateID_ == 0) // Custom Message Text
                    {
                        tabControl1.TabPages.Remove(tabHistoric);
                        tabControl1.TabPages.Add(tabHistoric);
                    }
                    else
                        tabControl1.TabPages.Remove(tabMessageText);

                    LoadHistoric();
                }

                currentAppointment.Write += new Outlook.ItemEvents_10_WriteEventHandler(currentAppointment_Write);

                appointmentDirty = false;
            }
            catch
            {
                SetCriticalErrorMode();
            }
        }

        private void currentAppointment_Write(ref bool Cancel)
        {
            if (appointmentEnabled && appointmentDirty)
            {
                SaveAppointment();
                appointmentDirty = false;
            }
        }

        // Occurs when the form region is closed.
        // Use this.OutlookItem to get a reference to the current Outlook item.
        // Use this.OutlookFormRegion to get a reference to the form region.
        private void SMSReminderRegion_FormRegionClosed(object sender, System.EventArgs e)
        {
            if (appointmentEnabled == true)
            {
                if (appointmentDirty)
                {
                    SaveAppointment();

                    appointmentDirty = false;
                }

                bool bReminderSelected = false;
                bool bTemplateSelected = false;

                foreach (ToolStripMenuItem item in tsReminders.DropDownItems)
                    if (item.Checked)
                        bReminderSelected = true;

                foreach (ToolStripMenuItem item in tsTemplates.DropDownItems)
                    if (item.Checked)
                        bTemplateSelected = true;

                if ((edContacts.Text.Trim().Length == 0) || !bReminderSelected || !bTemplateSelected ||
                    ((customMsgItem.Checked) && (edMessage.Text.Trim().Length == 0)))
                    MessageBox.Show("Debe completar todos los campos para configurar el envio correctamente.", "Movistar SMS",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        #endregion

        #region Save Control

        private void edField_TextChanged(object sender, EventArgs e)
        {
            appointmentDirty = true;
        }

        private void SaveAppointment()
        {
            try
            {
                Appointments currentApp = (from apps in remindersDB.Appointments
                                           where apps.OutlookID == currentAppointment.GlobalAppointmentID.Trim()
                                           select apps).Single();

                var oldReminders = from apprem in remindersDB.AppointmentReminders
                                   where apprem.AppointmentID_ == currentApp.AppointmentID_
                                   select apprem;

                remindersDB.AppointmentReminders.DeleteAllOnSubmit(oldReminders);
                remindersDB.SubmitChanges();

                currentApp.To = edContacts.Text.Trim();
                currentApp.CustomMessage = edMessage.Text.Trim();

                if (customMsgItem.Checked)  // Custom message
                    currentApp.TemplateID_ = 0;
                else
                {
                    foreach (ToolStripMenuItem item in tsTemplates.DropDownItems) // Template message
                        if (item.Checked)
                        {
                            currentApp.TemplateID_ = (int)item.Tag;  // TemplateID was saved on MenuItem tag
                            break;
                        }
                }

                foreach (ToolStripMenuItem item in tsReminders.DropDownItems)
                    if (item.Checked)
                    {
                        AppointmentReminders newAppReminder = new AppointmentReminders()
                        {
                            AppointmentID_ = currentApp.AppointmentID_,
                            ReminderID_ = (int)item.Tag  // ReminderID was saved on MenuItem tag
                        };

                        remindersDB.AppointmentReminders.InsertOnSubmit(newAppReminder);
                    }

                remindersDB.SubmitChanges();
            }
            catch
            {
                SetCriticalErrorMode();
            }
        }

        #endregion

        #region Create/Remove Configuration

        private void btCreateNewConfig_Click(object sender, EventArgs e)
        {
            try
            {
                if (currentAppointment.GlobalAppointmentID == null)
                {
                    MessageBox.Show("Debe salvar la cita antes de poder configurar un aviso por SMS.", "Movistar SMS",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                Appointments newAppointment = new Appointments()
                {
                    OutlookID = currentAppointment.GlobalAppointmentID.Trim(),
                    Occurs = currentAppointment.Start,
                };

                if (currentAppointment.Subject.Length <= 100)
                    newAppointment.Subject = currentAppointment.Subject;
                else
                    newAppointment.Subject = currentAppointment.Subject.Substring(0, 100);

                remindersDB.Appointments.InsertOnSubmit(newAppointment);

                remindersDB.SubmitChanges();

                LoadReminderAndTemplateControls();

                tabControl1.TabPages.Remove(tabNoConfig);
                tabControl1.TabPages.Add(tabConfig);
                tabControl1.TabPages.Add(tabHistoric);
                tabConfig.Focus();

                edContacts.Focus();

                appointmentDirty = false;
                appointmentEnabled = true;
            }
            catch
            {
                SetCriticalErrorMode();
            }
        }

        private void btRemoveConfig_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("¿Está seguro de que desea eliminar este aviso?", "Movistar SMS", MessageBoxButtons.OKCancel,
                MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                return;

            try
            {
                Appointments oldAppointment = (from apps in remindersDB.Appointments
                                               where apps.OutlookID == currentAppointment.GlobalAppointmentID.Trim()
                                               select apps).Single();

                var oldReminders = from apprem in remindersDB.AppointmentReminders
                                   where apprem.AppointmentID_ == oldAppointment.AppointmentID_
                                   select apprem;

                var oldHistorics = from his in remindersDB.Historic
                                   where his.AppointmentID_ == oldAppointment.AppointmentID_
                                   select his;

                remindersDB.Historic.DeleteAllOnSubmit(oldHistorics);
                remindersDB.AppointmentReminders.DeleteAllOnSubmit(oldReminders);
                remindersDB.Appointments.DeleteOnSubmit(oldAppointment);

                remindersDB.SubmitChanges();

                tabControl1.TabPages.Add(tabNoConfig);
                tabControl1.TabPages.Remove(tabConfig);
                tabControl1.TabPages.Remove(tabMessageText);
                tabControl1.TabPages.Remove(tabHistoric);
                tabNoConfig.Focus();

                appointmentDirty = false;
                appointmentEnabled = false;
            }
            catch
            {
                SetCriticalErrorMode();
            }
        }

        #endregion

        #region DropDownMenus

        private void LoadReminderAndTemplateControls()
        {
            LoadReminderAndTemplateControls(-1, null);  //No template either reminders selected
        }

        private void LoadReminderAndTemplateControls(int selectedTemplateID_, int[] selectedReminderID_)
        {
            var reminders = from rem in remindersDB.Reminders
                            select rem;

            if (reminders.Count() > 0)
            {
                string selectedItemName = "";

                // Load reminders choices

                foreach (Reminders reminder in reminders)
                {
                    ToolStripItem newItem = tsReminders.DropDownItems.Add(reminder.Name, null, OnItemClick);
                    newItem.ToolTipText = "Programación: " + reminder.Days + " dias, " + reminder.Hours + " Horas y " + reminder.Minutes + " minutos";
                    newItem.Tag = reminder.ReminderID_;

                    if (selectedReminderID_ != null)
                    {
                        foreach (int i in selectedReminderID_)
                            if (reminder.ReminderID_ == i)
                            {
                                ((ToolStripMenuItem)newItem).Checked = true;
                                selectedItemName = newItem.Text;
                            }
                    }
                }

                if (selectedReminderID_ == null)
                    tsReminders.Text = "Pulse para seleccionar la frecuencia de los envíos...";
                else if (selectedReminderID_.Count() == 1)
                    tsReminders.Text = selectedItemName + ". Pulse para modificar";
                else
                    tsReminders.Text = "Múltiples programaciones seleccionadas. Pulse para modificar";

                tsReminders.ToolTipText = "Pulse para seleccionar la frecuencia de los envíos...";
            }
            else
            {
                tsReminders.Text = "No existen programaciones definidas para seleccionar";
                tsReminders.ToolTipText = "No existen programaciones definidas para seleccionar";
                tsReminders.Enabled = false;
            }

            // Load template choices

            var templates = from tem in remindersDB.Templates
                            select tem;

            if (templates.Count() > 0)
            {
                foreach (Templates template in templates)
                {
                    ToolStripItem newItem = tsTemplates.DropDownItems.Add(template.Name, null, OnItemClick);
                    newItem.ToolTipText = "Mensaje: " + template.Text;
                    newItem.Tag = template.TemplateID_;

                    if (template.TemplateID_ == selectedTemplateID_)
                    {
                        ((ToolStripMenuItem)newItem).Checked = true;
                        tsTemplates.Text = template.Name + ". Pulse para modificar";
                    }

                    newItem = tsTemplatesCustomMessage.DropDownItems.Add(template.Name, null, OnItemClick);
                    newItem.ToolTipText = template.Text;
                    newItem.Tag = template.TemplateID_;
                }

                // Add custom message text MenuItem

                customMsgItem = (ToolStripMenuItem)tsTemplates.DropDownItems.Add("Texto del mensaje personalizado", null, OnItemClick);
                customMsgItem.ToolTipText = "Seleccione esta opción para escribir un texto personalizado";
                customMsgItem.Tag = 0;

                if (selectedTemplateID_ == 0)
                {
                    ((ToolStripMenuItem)customMsgItem).Checked = true;
                    tsTemplates.Text = "Mensaje Personalizado. Pulse sobre la pestaña 'Mensaje' para editar";
                }

                if (selectedTemplateID_ == -1) // No template selected
                {
                    tsTemplates.Text = "Pulse para seleccionar la plantilla del mensaje...";
                    tsTemplates.ToolTipText = "Pulse para seleccionar la plantilla del mensaje...";
                }
            }
            else
            {
                tsTemplates.Text = "No existen plantillas definidas para seleccionar";
                tsTemplates.ToolTipText = "No existen plantillas definidas para seleccionar";
                tsTemplates.Enabled = false;
            }
        }

        private void OnItemClick(object sender, EventArgs e)
        {
            try
            {
                ToolStripMenuItem senderOption = (ToolStripMenuItem)sender;

                appointmentDirty = true;

                if (senderOption.OwnerItem.Equals(tsReminders))  // Reminder item selected
                {
                    senderOption.Checked = !senderOption.Checked;

                    int selectedItems = 0;
                    string selectedItemName = "";

                    foreach (ToolStripMenuItem item in tsReminders.DropDownItems)
                        if (item.Checked)
                        {
                            selectedItemName = item.Text;
                            selectedItems++;
                        }

                    if (selectedItems == 0)
                        tsReminders.Text = "Pulse para configurar la frecuencia de los envíos...";
                    else
                        if (selectedItems > 1)
                            tsReminders.Text = "Múltiples programaciones seleccionadas. Pulse para modificar";
                        else
                            tsReminders.Text = selectedItemName + ". Pulse para modificar";
                }
                else if (senderOption.OwnerItem.Equals(tsTemplates)) // Template item selected
                {
                    if (sender.Equals(customMsgItem))  // Click on Custom Message
                    {
                        if (!senderOption.Checked)  // If custom message option was not previously selected
                        {
                            tabControl1.TabPages.Remove(tabHistoric);
                            tabControl1.TabPages.Add(tabMessageText);
                            tabControl1.TabPages.Add(tabHistoric);
                            tsTemplates.Text = "Mensaje Personalizado. Pulse sobre la pestaña 'Mensaje' para editar";
                            tabMessageText.Focus();
                        }
                        else // If custom message option was already selected just focus
                        {
                            tabMessageText.Focus();
                            return;
                        }
                    }
                    else
                    {
                        if (customMsgItem.Checked)
                            tabControl1.TabPages.Remove(tabMessageText);

                        tsTemplates.Text = senderOption.Text + ". Pulse para modificar";
                    }

                    foreach (ToolStripMenuItem item in tsTemplates.DropDownItems) // Reset all options and check selected
                        item.Checked = false;
                    senderOption.Checked = true;
                }
                else if (senderOption.OwnerItem.Equals(tsTemplatesCustomMessage))  // Custom Template on Message tab selected
                {
                    edMessage.Text = senderOption.ToolTipText;
                }
            }
            catch
            {
                SetCriticalErrorMode();
            }
        }

        #endregion

        #region Historic Tab

        private void LoadHistoric()
        {
            lbHistoric.Items.Clear();

            var his = from h in remindersDB.Historic
                      where h.AppointmentID_ == currentAppID
                      orderby h.Date descending
                      select h;

            if (his.Count() > 0)
                foreach (Historic h in his)
                {
                    lbHistoric.Items.Add(h.Date.ToShortDateString() + " (" + h.Date.ToLongTimeString() + "). " +
                        (h.SentOK ? "Mensaje Enviado" : "Mensaje Fallido") + ". Para: " + h.SentTo + ". Texto:" +
                        h.Message);
                }

            lbHistoric.Enabled = (his.Count() > 0);
            btEraseHistoric.Enabled = ((currentAppOccurs < DateTime.Now) && (his.Count() > 0)); // Allow deleting only for past appointment
        }

        private void btEraseHistoric_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("¿Está seguro de que desea eliminar los datos de envíos pasados?", "Movistar SMS",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                    return;

                var his = from h in remindersDB.Historic
                          where h.AppointmentID_ == currentAppID
                          select h;

                remindersDB.Historic.DeleteAllOnSubmit(his);

                remindersDB.SubmitChanges();

                LoadHistoric();
            }
            catch
            {
                SetCriticalErrorMode();
            }
        }

        #endregion

        #region Contacts

        private void edNumericField_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!((e.KeyChar == (char)8) || (e.KeyChar == (char)';') || (e.KeyChar == (char)'+') ||
                ((e.KeyChar >= (char)'0') && (e.KeyChar <= (char)'9'))))
                e.KeyChar = (char)0;
        }

        private void edContacts_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                string[] numbers = edContacts.Text.Split(';');

                edContacts.Text = "";

                foreach (string number in numbers)
                {
                    if (number.Trim().Length > 0)
                    {
                        if (edContacts.Text.Length > 0)
                            edContacts.Text += " ; ";

                        edContacts.Text += number.Trim();
                    }
                }
            }
            catch
            {
                SetCriticalErrorMode();
            }
        }

        private void btContacts_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    Outlook.Application app = new Outlook.Application();

            //    Outlook.SelectNamesDialog dlgNames = app.Session.GetSelectNamesDialog();

            //    dlgNames.NumberOfRecipientSelectors = Microsoft.Office.Interop.Outlook.OlRecipientSelectors.olShowTo;
            //    dlgNames.ForceResolution = false;

            //    if (dlgNames.Display())
            //    {
            //        foreach (Outlook.Recipient rec in dlgNames.Recipients)
            //        {
            //        }
            //    }
            //}
            //catch
            //{
            //    SetCriticalErrorMode();
            //}
        }

        #endregion

        private void SetCriticalErrorMode()
        {
            tabControl1.TabPages.Remove(tabNoConfig);
            tabControl1.TabPages.Remove(tabConfig);
            tabControl1.TabPages.Remove(tabMessageText);
            tabControl1.TabPages.Remove(tabHistoric);
            tabControl1.TabPages.Add(tabNoConfig);

            btCreateConfig.Visible = false;

            lbNoConfig.Text = "Ha ocurrido un error inesperado en la aplicación.\n" +
                "Si el error persiste reinstale la aplicación.\n";

            appointmentEnabled = false;
        }
    }
}

